#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <vector>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <functional>
#include <semaphore.h>
#include <jsoncpp/json/json.h>
#include <sys/select.h>
#include <mysql/mysql.h>
using namespace std;
void CutTwoLine(const string &line, string &line_front, string &line_back, string ch)
{
    int pos = line.find(ch);
    line_front = line.substr(0, pos);
    line_back = line.substr(pos + ch.size());
}
bool GetQueryString(string &query_string) // 获取环境变量中的参数
{
    bool result = false;
    string method = getenv("METHOD");
    if (method == "GET")
    {
        query_string = getenv("QUERY_STRING");
        result = true;
    }
    else if (method == "POST")
    {
        int content_length = stoi(getenv("CONTENT_LENGTH"));
        for (int i = 0; i < content_length; i++)
        {
            char ch = 'x';
            int n = read(0, &ch, 1);
            if (n > 0)
            {
                query_string.push_back(ch);
            }
        }
        result = true;
    }
    return result;
}
bool InsertSql(string sql)  //连接数据库，根据传过来的参数信息修改数据库信息
{
    MYSQL *conn = mysql_init(nullptr);
    if (mysql_real_connect(conn, "127.0.0.1", "zqj", "1234567", "helloworld", 8080, nullptr, 0) == nullptr)
    {
        cerr << "mysql connect fault" << endl;
    }
    int ret = mysql_query(conn, sql.c_str());
    cerr << "result: " << ret << endl;
    mysql_close(conn);
}
void Deal_Query_String(string &str)     //将传参传过来的字符串进行转义
{
    int n = str.size();
    string ans;
    for (int i = 0; i < n; i++)
    {
        if (str[i] == '%')
        {
            if (str[i + 2] == '0')
            {
                ans.push_back(' ');
            }
            else
            {
                ans += "'";
            }
            i += 2;
        }
        else
        {
            ans.push_back(str[i]);
        }
    }
    str = ans;
}
int main()
{
    string query_string;
    if (GetQueryString(query_string))
    {
        string str1;
        string str2;
        CutTwoLine(query_string, str1, str2, "&");
        string name1;
        string name2;
        string value1;
        string value2;
        CutTwoLine(str1, name1, value1, "=");
        CutTwoLine(str2, name2, value2, "=");
        cerr << name1 << ": " << value1 << endl;
        cerr << name2 << ": " << value2 << endl;
    }
    Deal_Query_String(query_string);
    InsertSql(query_string);

    return 0;
}
